package com.night.service.impl;

import cn.hutool.json.JSONUtil;
import com.night.entity.Order;
import com.night.service.OrderService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.night.common.RedisConstants.ORDER_CACHE_TTL;
import static com.night.common.RedisConstants.ORDER_KEY_PREFIX;

/**
 * @Author: chen yang
 * @Date: 2025/3/23 22:00
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Order getById(Long id) {

        String orderJson = stringRedisTemplate.opsForValue().get(ORDER_KEY_PREFIX + id);

        if (StringUtils.isNotBlank(orderJson)) {
            return JSONUtil.toBean(orderJson, Order.class);
        }

        Order order = getFromBD(id);

        if (order == null) {
            return null;
        }
        String jsonStr = JSONUtil.toJsonStr(order);
        stringRedisTemplate.opsForValue().set(ORDER_KEY_PREFIX + id, jsonStr, ORDER_CACHE_TTL, TimeUnit.SECONDS);
        return order;
    }


    private Order getFromBD(Long id) {

        System.out.println("get from db");

        if (id == null || id != 1) {
            return null;
        }
        Order order = new Order();
        order.setId(1L);
        order.setCode("code");
        order.setName("name");
        return order;
    }
}
